import axios from './axios';

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  } else if (response.status === 401) {
    // console.log('401 auth error');
    const error = new Error(response.statusText);
    error.response = response;
    throw error;
  } else {
    const error = new Error(response.statusText);
    error.response = response;
    throw error;
  }
}

function parseJSON(response) {
  return response.data;
}

export function request(url, options, callback) {
  // axios.defaults.headers.post['Content-Type'] = 'application/json';
  axios
  .post(url, options)
  .then(checkStatus)
  .then(parseJSON)
  .then(data => callback(data))
  .catch(err => (err));
}

// get fetch methods
export function GET(url, callback) {
  const options = {
    mode: 'cors',
    method: 'PUT',
    credentials: 'omit',
  };
  request(url, options, callback);
}
// post body={}
export function POST(url, body) {
  // mock online http api server
  const mock = process.env.MOCK_ENV;
  return axios
  .post(mock ? url : '', body)
  .then(checkStatus)
  .then(parseJSON);
}

export default { request, GET, POST };
